﻿using JsonAndDependencyInjection.DoMain;
using JsonAndDependencyInjection.Interface;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JsonAndDependencyInjection.Implementation
{
    public class EfRespository<T> : IRespository<T> where T : BaseEntity
    {
        private readonly Admin4000Context db;
        public EfRespository(Admin4000Context admin4000)
        {
            db = admin4000;
        }
        //实体对象
        private DbSet<T> _entity;
        protected DbSet<T> Entity
        {
            get
            {
                if (_entity == null) _entity = db.Set<T>();
                return _entity;
            }
        }
        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }
        public void Delete(T entity)
        {
            this._entity.Remove(entity);
            db.SaveChanges();
        }

        public void Delete(int id)
        {
            var Row = Table.Where(x => x.Id == id).FirstOrDefault();
            Delete(Row);
        }

        public T GetById(int id)
        {
            return _entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void Insert(T entity)
        {
            _entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            _entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            _entity.Update(entity);
            db.SaveChanges();
        }
    }
}
